<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售价" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入售价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售卖状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择售卖状态"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in dish_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="餐品类型" prop="categoryType">
        <el-select
          v-model="queryParams.categoryType"
          placeholder="请选择餐品类型"
          clearable
          style="width: 200px"
        >
          <el-option label="前厅" value="前厅" />
          <el-option label="后厨" value="后厨" />
          <el-option label="吧台" value="吧台" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['restaurant:restaurant:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['restaurant:restaurant:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['restaurant:restaurant:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['restaurant:restaurant:import']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['restaurant:restaurant:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="restsurantList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="售价" align="center" prop="price" />
      <el-table-column label="库存数量" align="center" prop="num" />
      <el-table-column label="描述信息" align="center" prop="description" />
      <el-table-column label="餐品类型" align="center" prop="categoryType" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.categoryType === '前厅'" type="success">前厅</el-tag>
          <el-tag v-else-if="scope.row.categoryType === '后厨'" type="primary">后厨</el-tag>
          <el-tag v-else-if="scope.row.categoryType === '吧台'" type="warning">吧台</el-tag>
          <el-tag v-else type="info">{{ scope.row.categoryType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="售卖新状" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="dish_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['restaurant:restaurant:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['restaurant:restaurant:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改菜单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="restsurantRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入售价" />
        </el-form-item>

        <el-form-item label="库存数量" prop="num">
          <el-input v-model.number="form.num" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述信息" />
        </el-form-item>
        <el-form-item label="餐品类型" prop="categoryType">
          <el-select v-model="form.categoryType" placeholder="请选择餐品类型">
            <el-option label="前厅" value="前厅" />
            <el-option label="后厨" value="后厨" />
            <el-option label="吧台" value="吧台" />
          </el-select>
        </el-form-item>
        <el-form-item label="售卖新状" prop="status">
          <el-select v-model="form.status" placeholder="请选择售卖新状">
            <el-option
              v-for="dict in dish_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入按钮操作 -->
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="uploadOpen"
      width="400px"
      append-to-body
    >
      <!-- :action="upload.url + '?updateSupport=' + upload.updateSupport" -->

      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="
          '/dev-api/restaurant/menu/importData' +
          '?updateSupport=' +
          updateSupport
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="updateSupport" />是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click.stop="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="uploadOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Menu">
import {
  listRestsurant,
  getRestsurant,
  delRestsurant,
  addRestsurant,
  updateRestsurant,
  deleteLists,
} from "@/api/restaurant/restsurant";
import { getToken } from "@/utils/auth";
import { ref } from "vue";
const { proxy } = getCurrentInstance();
const { dish_status } = proxy.useDict("dish_status");

const restsurantList = ref([]);
const restFlavorList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const checkedRestFlavor = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const uploadOpen = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    price: null,
    status: null,
    categoryType: null,
  },
  rules: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    price: [{ required: true, message: "售价不能为空", trigger: "blur" }],
    num: [{ required: true, message: "库存数量不能为空", trigger: "blur" }],
    description: [
      { required: true, message: "描述信息不能为空", trigger: "blur" },
    ],
    categoryType: [
      { required: true, message: "餐品类型不能为空", trigger: "change" },
    ],
    status: [
      { required: true, message: "售卖新状不能为空", trigger: "change" },
    ],
  },
});
const updateSupport = ref(false);
const { queryParams, form, rules } = toRefs(data);
const upload = reactive({
  title: "导入菜单管理",
  open: false,
  url: "/restaurant/menu/importData",
  isUploading: false,
  updateSupport: false,
  headers: {
    Authorization: `Bearer ${getToken()}`,
  },
});

/** 查询菜单管理列表 */
function getList() {
  loading.value = true;
  listRestsurant(queryParams.value).then((response) => {
    restsurantList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    price: null,
    num: null,
    description: null,
    categoryType: '后厨',
    status: null,
    createTime: null,
    updateTime: null,
  };
  restFlavorList.value = [];
  proxy.resetForm("restsurantRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加菜单管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getRestsurant(_id).then((response) => {
    response.data.status = response.data.status * 1;
    form.value = response.data;
    restFlavorList.value = response.data.restFlavorList;
    open.value = true;
    title.value = "修改菜单管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["restsurantRef"].validate((valid) => {
    if (valid) {
      form.value.restFlavorList = restFlavorList.value;
      if (form.value.id != null) {
        updateRestsurant(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRestsurant(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除菜单管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      if (Array.isArray(_ids)) {
        if (_ids.length > 1) {
          return deleteLists({
            ids: _ids,
          });
        } else {
          return delRestsurant(_ids[0]);
        }
      } else {
        // 单个删除
        return delRestsurant(_ids);
      }
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 菜品喜好序号 */
function rowRestFlavorIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 菜品喜好添加按钮操作 */
function handleAddRestFlavor() {
  let obj = {};
  obj.name = "";
  obj.value = "";
  restFlavorList.value.push(obj);
}

/** 菜品喜好删除按钮操作 */
function handleDeleteRestFlavor() {
  if (checkedRestFlavor.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的菜品喜好数据");
  } else {
    const restFlavors = restFlavorList.value;
    const checkedRestFlavors = checkedRestFlavor.value;
    restFlavorList.value = restFlavors.filter(function (item) {
      return checkedRestFlavors.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleRestFlavorSelectionChange(selection) {
  checkedRestFlavor.value = selection.map((item) => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "restaurant/menu/export",
    {
      ...queryParams.value,
    },
    `restsurant_${new Date().getTime()}.xlsx`
  );
}

/** 导入按钮操作 */
function handleImport() {
  uploadOpen.value = true;
  console.log(uploadOpen.value);
}

function submitFileForm() {
  proxy.$refs.upload.submit();
  uploadOpen.value = false;
}
//文件上传进度回调
function handleFileUploadProgress(progress) {
  upload.progress = progress;
  upload.isUploading = true;
}
//上传成功回调
function handleFileSuccess() {
  upload.isUploading = false;
  proxy.$modal.msgSuccess("导入成功");
  upload.progress = 100;
  uploadOpen.value = false;
  proxy.$refs.upload.clearFiles();
  getList();
}
function importTemplate() {
  proxy.download(
    "restaurant/menu/importTemplate",
    {},
    `菜单管理导入模板_${new Date().getTime()}.xlsx`
  );
}
getList();
</script>

<style scoped lang="scss">
// ==================== 响应式适配 ====================

// 平板端适配 (iPad: 600px - 1024px)
@media screen and (min-width: 600px) and (max-width: 1024px) {
  .app-container {
    padding: 16px;

    // 搜索表单平板适配
    :deep(.el-form) {
      .el-form-item {
        margin-right: 12px;

        .el-input,
        .el-select {
          width: 180px !important;
        }
      }
    }

    // 工具栏按钮平板适配
    .mb8 {
      margin-bottom: 12px;

      .el-col {
        .el-button {
          margin: 0 8px 8px 0 !important;
        }
      }
    }

    // 表格平板适配
    :deep(.el-table) {
      font-size: 13px;

      .el-table__header th {
        padding: 10px 0;
      }

      .el-table__body td {
        padding: 10px 0;
      }
    }
  }

  // 对话框平板适配
  :deep(.el-dialog) {
    width: 600px !important;
    margin: 5vh auto !important;

    .el-dialog__header {
      padding: 16px 20px;
    }

    .el-dialog__body {
      padding: 16px 20px;
      max-height: 70vh;
      overflow-y: auto;
    }

    .el-dialog__footer {
      padding: 12px 20px;
    }
  }
}

// 手机端适配 (< 600px)
@media screen and (max-width: 599px) {
  .app-container {
    padding: 10px;

    // 搜索表单移动端适配
    :deep(.el-form) {
      .el-form-item {
        display: block;
        margin-right: 0;
        margin-bottom: 12px;

        .el-form-item__label {
          display: block;
          text-align: left;
          margin-bottom: 4px;
          width: 100% !important;
        }

        .el-form-item__content {
          margin-left: 0 !important;

          .el-input,
          .el-select {
            width: 100% !important;
          }
        }

        &:last-child {
          .el-form-item__content {
            display: flex;
            gap: 8px;

            .el-button {
              flex: 1;
            }
          }
        }
      }
    }

    // 工具栏按钮移动端适配
    .mb8 {
      margin-bottom: 10px;

      .el-col {
        width: 100% !important;
        max-width: 100% !important;
        margin-bottom: 8px;

        .el-button {
          width: 100%;
          margin: 0 0 8px 0 !important;
        }
      }
    }

    // 表格移动端适配
    :deep(.el-table) {
      font-size: 12px;

      .el-table__header th {
        padding: 8px 0;
        font-size: 12px;
      }

      .el-table__body td {
        padding: 8px 0;
        font-size: 12px;
      }

      // 隐藏部分列以适应小屏幕
      .el-table-column--selection {
        .cell {
          padding: 0 4px;
        }
      }

      .el-button {
        padding: 4px 8px;
        font-size: 12px;
        margin: 2px;
      }
    }

    // 分页移动端适配
    :deep(.el-pagination) {
      justify-content: center;
      flex-wrap: wrap;
      padding: 10px 0;

      .el-pagination__sizes {
        margin: 0 0 8px 0;
      }

      .el-pagination__jump {
        margin-left: 0;
        margin-top: 8px;
      }
    }
  }

  // 对话框移动端适配
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 10px auto !important;

    .el-dialog__header {
      padding: 12px 16px;
    }

    .el-dialog__body {
      padding: 12px 16px;
      max-height: calc(100vh - 150px);
      overflow-y: auto;
    }

    .el-dialog__footer {
      padding: 10px 16px;

      .el-button {
        width: 48%;
        margin: 0 1%;
      }
    }

    .el-form {
      .el-form-item {
        display: block;
        margin-bottom: 12px;

        .el-form-item__label {
          display: block;
          text-align: left;
          margin-bottom: 4px;
          width: 100% !important;
        }

        .el-form-item__content {
          margin-left: 0 !important;

          .el-input,
          .el-select,
          .el-input-number {
            width: 100% !important;
          }

          .el-textarea {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>
